package com.zxp.mall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxp.mall.common.utils.HttpUtils;
import com.zxp.mall.common.utils.PageUtils;
import com.zxp.mall.common.utils.Query;
import com.zxp.mall.member.dao.MemberDao;
import com.zxp.mall.member.entity.MemberEntity;
import com.zxp.mall.member.entity.MemberLevelEntity;
import com.zxp.mall.member.exception.PhoneExistException;
import com.zxp.mall.member.exception.UsernameExistException;
import com.zxp.mall.member.service.MemberLevelService;
import com.zxp.mall.member.service.MemberService;
import com.zxp.mall.member.vo.MemberGiteeUserInfo;
import com.zxp.mall.member.vo.MemberLoginVo;
import com.zxp.mall.member.vo.MemberRegisterVo;
import com.zxp.mall.member.vo.MemberSocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void registe(MemberRegisterVo vo) {
        MemberEntity memberEntity = new MemberEntity();
//        检查用户名和手机号是否唯一
        checkUsernameUnique(vo.getUsername());
        memberEntity.setUsername(vo.getUsername());
        memberEntity.setNickname(vo.getUsername());
        checkPhoneUnique(vo.getPhone());
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setCreateTime(new Date());
//        密码加密器
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);
//        默认等级
        MemberLevelEntity levelEntity = memberLevelService.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());

        this.save(memberEntity);
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        int count = this.count(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        int count = this.count(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        MemberEntity entity = this.getOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if (entity == null) {
//            没有匹配的
            return null;
        } else {
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(password, passwordDb);
            if (matches) {
//              登录成功
                return entity;
            } else {
//               登录失败
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(MemberSocialUser user) throws Exception {
        Map<String, String> query = new HashMap<>();
        Map<String, String> headers = new HashMap<>();
        query.put("access_token", user.getAccess_token());
        HttpResponse httpResponse = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", headers, query);
        MemberGiteeUserInfo userInfo = JSON.parseObject(EntityUtils.toString(httpResponse.getEntity()),
                MemberGiteeUserInfo.class);
//        注册和登录合并逻辑
        String uid = String.valueOf(userInfo.getId());
        MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if(memberEntity!=null) {
//            已经注册 修改信息
            MemberEntity update = new MemberEntity();
            update.setSocialUid(uid);
            update.setAccessToken(user.getAccess_token());
            update.setExpiresIn(String.valueOf(user.getExpires_in()));

            this.updateById(update);

            memberEntity.setAccessToken(user.getAccess_token());
            memberEntity.setExpiresIn(String.valueOf(user.getExpires_in()));
            return memberEntity;
        }else{
//            没注册 需要注册
            MemberEntity member = new MemberEntity();
            member.setNickname(userInfo.getName());
            member.setUsername(userInfo.getName());
            member.setEmail(userInfo.getEmail());
            member.setExpiresIn(String.valueOf(user.getExpires_in()));
            member.setSocialUid(uid);
            member.setAccessToken(user.getAccess_token());
            this.save(member);
            return member;
        }
    }

}